// SlagCar/WaybillList/WaybillList.js
let listBehavior = require('../../behavior/list')
Page({
  behaviors: [ listBehavior, ],

  /**
   * 页面的初始数据
   */
  data: {
    tabList: ['运单列表','运单统计'], //顶部标签
    tabActive: 0, //标签选中索引

    title: '运输列表',
    baseQuery: [],

    filterList: ['全部','审核中','已审核'],
    filter: '全部',  //过滤选中按钮： 全部、审核中、已审核、退回
    page: 1,
    total: 0,
    limit: 10,
    curTotal: 0,  //趟数

    activeNames: [],  //折叠面板
    deliveryList: [],  //统计工地列表
    driver_amount_sum: 0,   //统计金额

    driver_end_time_start: '',  //开始时间
    driver_end_time_end: '',  //结束时间
    curShowType: '',
    showCalendarStart: false,
    showCalendarEnd: false,
  },
  onTabTap(e){
    let { i, } = e.currentTarget.dataset;

    if (i === 1 && !this.data.deliveryList.length){
      this.getOrderCount();
    }
    this.setData({
      tabActive: i,
    })
  },
  //查询过滤数据
  bindFilter(e){
    let {name} = e.currentTarget.dataset;
    this.setData({filter: name});
    // this.getRefreshPage();
    this.getFirstPage();
  },

  //获取数据
  getDataList(){
    let {page,limit,filter,list,baseQuery} = this.data
    let total = 0,curTotal = 0,
      obj = {};
    let url = 'DynamicQuery/query_dynamic_v3',
      post = {"oby":"muck_waybill_main.row_id","table_id":"muck_waybill_main",page,limit},
      where = [...baseQuery];

    if (filter === '审核中'){
      where.push(
        {CompareWith:"muck_waybill_main.is_auditing_1",Operator:"=",CompareValue:false,"or":0},
        // {CompareWith: "muck_waybill_main.auditing_1_user_row_id", Operator: "is null", CompareValue: "", or: 0}
      )
    }
    if (filter === '已审核'){
      where.push(
        {CompareWith:"muck_waybill_main.is_auditing_1",Operator:"=",CompareValue:true,"or":0},
      )
    }
    if (filter === '退回'){
      where.push(
        {CompareWith:"muck_waybill_main.is_auditing_1",Operator:"=",CompareValue:false,"or":0},
        {CompareWith: "muck_waybill_main.staff_mark", Operator: "<>", CompareValue: "", or: 0}
      )
    }
    if (where.length) post.SearchWhere = {filters: where,type: 'and'};
    wx.$post(3,url,post).then(res => {
      if (res.errcode != 0) return;
      if (res.data.row){
        curTotal = res.data.sum[0];
        curTotal = curTotal['填写趟次'] || 0;
        total = res.data.total
        let rows = res.data.row;
        if(page !== 1) rows = [ ...list,...rows, ]
        obj = {curTotal,total,list: rows,page};
      }
      this.setData(obj);
    });
  },

  //获取统计列表
  getOrderCount(){
    let url = 'ZTAuth/muck_order_complete_count_driver_lv1',
      {driver_end_time_start,driver_end_time_end,userType} = this.data,
      post = {
        "driver_end_time_start": driver_end_time_start,
        "driver_end_time_end": driver_end_time_end,
        "is_all": userType !== 'driver',
        "only_my_destination": userType === 'disposal',
        "only_my_suoshuchedui": userType === 'carTeam'
      }
      wx.showLoading({mask: true});
      wx.$post(5,url,post).then(res => {
        if (res.errcode != 0) return
        wx.hideLoading();
        let row0 = res.data.row[0] || {},
          {driver_amount_sum,deliveries,destination_amount_sum} = row0;
        driver_amount_sum = userType === 'disposal' ? destination_amount_sum : driver_amount_sum
        this.setData({deliveryList: deliveries,driver_amount_sum,activeNames: []})
      })
  },
  bindClick(e){
    let detail = e.detail,
      { activeNames,deliveryList } = this.data,
      index = detail[detail.length -1],
      value = deliveryList[index];
    if (!value){
      activeNames = detail;
      this.setData({activeNames});
      return
    }
    if (activeNames.includes(index)){
      activeNames = activeNames.filter(item => item != index)
    }else {
      activeNames.push(index);
      if (!value.destinationList){
        this.getOrderCountDtl(value.reference1_all_delivery).then(res => {
          deliveryList[index].destinationList = res;
          this.setData({deliveryList})
        });
      }
    }
    activeNames = detail;
    this.setData({activeNames})
  },
  getOrderCountDtl(id){
    return new Promise(resolve => {
      wx.showLoading({mask: true})
      let url = 'ZTAuth/muck_order_complete_count_driver_lv2',
        {driver_end_time_start,driver_end_time_end,userType} = this.data,
        post = {
          "driver_end_time_start": driver_end_time_start,
          "driver_end_time_end": driver_end_time_end,
          "reference1_all_delivery": id,
          "is_all": userType !== 'driver',
          "only_my_destination": userType === 'disposal',
          "only_my_suoshuchedui": userType === 'carTeam'
        };
      wx.$post(5,url,post).then(res => {
        if (res.errcode != 0) return;
        wx.hideLoading();
        let data = res.data.row || [];
        resolve(data);
      })
    })
  },
  bindShowCalendar(e){
    let {type} = e.currentTarget.dataset,
      name = type === 'start' ? 'showCalendarStart' : 'showCalendarEnd';
    this.setData({[name]: !this.data[name],curShowType: type})
  },
  bindSelectDatetime(e){
    console.log(e);
    let {curShowType} = this.data,
      value = e.detail,
      name = curShowType === 'start' ? 'driver_end_time_start' : 'driver_end_time_end'
    this.setData({[name]: value})
  },

  //跳转运单详情
  navTo(e){
    let {url} = e.currentTarget.dataset;
    wx.navigateTo({url})
  },

  //订单统计跳转
  bindNavTo(e){
    //消纳场id
    let {destination,delivery} = e.currentTarget.dataset,
      {driver_end_time_start,driver_end_time_end} = this.data,
      where = [
        {
          "CompareWith":"muck_waybill_main.reference1_all_delivery",
          "Operator":"=",
          "CompareValue": delivery,
          "or":0
        },
        {
          "CompareWith":"muck_waybill_main.reference1_all_destination",
          "Operator":"=",
          "CompareValue": destination,
          "or":0
        },
        {
          CompareValue: driver_end_time_start + ' 00:00',
          CompareWith: "muck_waybill_main.driver_end_time",
          Operator: ">=",
          "or":0
        },
        {
          CompareValue: driver_end_time_end + ' 23:59:59',
          CompareWith: "muck_waybill_main.driver_end_time",
          Operator: "<=",
          "or":0
        },
      ];
    wx.setStorageSync('approveQuery',where);
    wx.navigateTo({
      url: '/SlagCar/ApproveView/ApproveView'
    })
  },

  // 获取员工信息
  getEmployeeData(){
    return new Promise(resolve => {
      let employee_row_id = wx.getStorageSync('employee_row_id');
      console.log(employee_row_id);
      if (!employee_row_id) {
        wx.$toast('没有员工信息');
        return
      }
      let post = {
        "oby":"all_employee_inf.row_id desc",
        "table_id":"all_employee_inf",
        "page":1,
        "limit":1,
        "SearchWhere":{
          "type": "and",
          "filters" : [
            {
              "CompareValue": employee_row_id,
              "CompareWith": "all_employee_inf.row_id",
              "Operator": "=",
              "or": 0
            }
          ]
        }

      }
      wx.$post(3,'DynamicQuery/query_dynamic_v3',post).then(res =>{
        if (res.errcode != 0 ) return;
        let data = res.data && res.data.row[0];
        if (!data){
          wx.$toast('没有员工信息');
          return
        }
        let suoshuchedui = data && data.suoshuchedui,
          suoshuxiaonachang = data && data.suoshuxiaonachang;
        this.setData({
          suoshuchedui,
          suoshuxiaonachang
        });
        resolve();
      })
    })
  },



  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    let userType = wx.getStorageSync('user_type'),
      title = '运输列表',
      baseQuery = [{CompareWith: "muck_waybill_main.is_used", Operator: "=", CompareValue: true, or: 0}],
      filterList = ['全部','审核中','已审核'];
    if (userType === 'driver'){
      let driver_row_id = wx.getStorageSync('driver_row_id')
      baseQuery.push({CompareWith: "muck_waybill_main.reference1_driver", Operator: "=", CompareValue: driver_row_id, or: 0});
      title = '我的任务';
      filterList = ['全部','审核中','已审核','退回']
    }
    let {query} = options,
      queryText = '';
    if (query === 'running'){
      baseQuery.push(
        {
          "CompareWith":"muck_waybill_main.driver_start_time",
          "Operator":"is not null",
          "CompareValue": "",
          "or":0
        },
        {
          "CompareWith":"muck_waybill_main.driver_end_time",
          "Operator":"is null",
          "CompareValue": "",
          "or":0
        },)
      queryText = '正在运输'
    } else if (query === 'today') {
      baseQuery.push(
        {
          "CompareWith":"dbo.FUN_query_add_day(0,muck_waybill_main.driver_end_time)",
          "Operator":"=",
          "CompareValue": 1,
          "or":0
        },)
      queryText = '今日趟数'
    }else if (query === 'month'){
      baseQuery.push(
        {
          "CompareWith":"datediff(month,muck_waybill_main.driver_end_time,getdate())",
          "Operator":"=",
          "CompareValue": 0,
          "or":0
        },)
      queryText = '本月趟数'
    }

    let today = wx.$util.formatDate(new Date(),'yyyy-MM-dd');

    if (userType === 'carTeam'){
      await this.getEmployeeData();
      let {suoshuchedui,} = this.data;
      if (!suoshuchedui) {
        wx.$toast('该员工没有设置所属车队')
      }
      baseQuery.push({
        "CompareWith": "muck_waybill_main.r_suoshuchedui",
        "Operator": "=",
        "CompareValue": suoshuchedui || 0,
        "or": 0
      })
    }
    if (userType === 'disposal') {
      await this.getEmployeeData();
      let {suoshuxiaonachang} = this.data;
      if (!suoshuxiaonachang) {
        wx.$toast('该员工没有设置所属消纳场')
      }
      baseQuery.push({
        "CompareWith": "muck_waybill_main.reference1_all_destination",
        "Operator": "=",
        "CompareValue": suoshuxiaonachang || 0,
        "or": 0
      })
    }

    this.setData({baseQuery,title,driver_end_time_start: today,driver_end_time_end: today,userType,filterList,queryText });



    this.getDataList();

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
